package com.ztjava.common.controller;

import java.io.File;

import com.jfinal.aop.Duang;
import com.jfinal.kit.Ret;
import com.ztjava.common.Common;
import com.ztjava.common.service.FilesService;
import com.ztjava.common.tool.files.QiniuTool;
import com.ztjava.core.Constant;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.tool.UploadTool;
import com.ztjava.core.tool.ViewTool;
import com.ztjava.ext.auth.annotation.UserMethod;
import com.ztjava.ext.auth.bean.AuthSession;

public class FilesBaseController extends BaseController{
	private static FilesService filesService = Duang.duang(FilesService.class);

	/***
	 * 保存上传文件
	 */
	@UserMethod
	public void doUpload(){
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		Ret ret;
		if(getPara("contentType","unknow").equals("html5")){
			ret = UploadTool.html5Upload(this, authSession.getId());
		}else {
			ret = UploadTool.upload(this, authSession.getId());
		}
		if(ret.getStr(Constant.RESULT).equals(Constant.ERROR)) {
			renderUpload(ret);
            return;
		}
		ret.set("localPath", ret.getStr("filePath"));
		ret.set("server","");
		
		String upload_type = getPara("upload_type","");
		if(upload_type.equals("")){
			upload_type = ViewTool.param(Common.COMMON_FILES_TYPE,Common.local);
		}
		switch (upload_type) {
			case Common.local:
				break;
			case Common.qiniu:
				File file = new File(ret.getStr("folerPath"));
				if (file.exists()) {
					ret.set("server",ViewTool.param(Common.COMMON_FILES_QINIU_CDN,""));
					ret.set("filePath", "/"+QiniuTool.postFile(file, getPara("directory","other")
							,authSession.getId()));
				}
				break;
			default:
				renderUpload(Ret.create(Constant.RESULT,Constant.ERROR).set(Constant.MESSAGE, "不可用的上传方式！"));
				return;
		}
		filesService.insertInfo(upload_type, ret, authSession.getId());
		renderUpload(ret);
	}
}
